package de.mhu.mandalaui.remote;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.map.ObjectMapper;

import de.mhu.mandalaui.Window;

public class RemoteRegistry {

	private Window window;
	private RemoteCallable callable;

	public RemoteRegistry(Window window, RemoteCallable ds) {
		this.window = window;
		this.callable = ds;
	}

	public Window getWindow() {
		return window;
	}
	
	public RemoteCallable getCallable() {
		return callable;
	}
	
	public String getUrl() {
		return getWindow().getRemoteUrl(this);
	}

	public void doRemoteCall(HttpServletRequest request,
			HttpServletResponse response, String requestId) {

		try {
			JsonFactory f = new JsonFactory();
			String data = request.getParameter("data");
			JsonNode in = null;
			if (data != null && !data.equals("undefined")) {
				try {
					ObjectMapper mapper = new ObjectMapper();
					JsonParser parser = f.createJsonParser(data);
					in = mapper.readTree(parser);
				} catch (Throwable t) {}
			}	
			response.setContentType("application/json");
			response.resetBuffer();
			response.setCharacterEncoding("UTF-8");
			JsonGenerator out = f.createJsonGenerator(response.getWriter());
	
			getCallable().doRemoteCall(in, out, requestId);
			out.close();
	
			response.flushBuffer();
		} catch (Throwable t) {
			t.printStackTrace();
		}
	}
	
}
